package com.liaofan.example;

import redis.clients.jedis.Jedis;

import java.util.Random;


/**
 * 要求：
 * 1、输入手机号，点击发送后随机生成6位数字码，2分钟有效
 * 2、输入验证码，点击验证，返回成功或失败
 * 3、每个手机号每天只能输入3次
 */
public class PhoneCode {
    String phoneNumber = "13408693331";

    public static void main(String[] args) {
        PhoneCode code = new PhoneCode();
        //code.putPhoneCode();
        code.getRedisCode(code.phoneNumber, "168419");
    }


    /**
     * 放入验证码
     */
    public void putPhoneCode
    () {
        Jedis jedis = new Jedis("192.168.153.129", 6379);
        PhoneCode phoneCode = new PhoneCode();
        String phoneCode_number = phoneCode.genratePhoneCode();
        String countKey = "Verify Phone Code" + phoneNumber + ":count";
        String codeKey = "Verify Phone Code" + phoneNumber + ":code";
        System.out.println(phoneCode_number);

        String sendCount = jedis.get(countKey);
        if (sendCount == null) {
            jedis.setex(countKey, 24 * 60 * 60, "1");
        } else if (Integer.parseInt(sendCount) < 2) {
            //发送次数+1
            jedis.incr(countKey);
        } else if (Integer.parseInt(sendCount) >= 3) {
            System.out.println("不能超过3次");
            jedis.close();
        }

        jedis.setex(codeKey, 120, phoneCode_number);
        jedis.close();
    }

    public void getRedisCode(String phoneNumber, String code) {
        Jedis jedis = new Jedis("192.168.153.129", 6379);
        String countKey = "Verify Phone Code" + phoneNumber + ":count";
        String codeKey = "Verify Phone Code" + phoneNumber + ":code";
        String rediscode = jedis.get(codeKey);
        if (rediscode.equals(code)) {
            System.out.println("通过");
        } else {
            System.out.println("不通过");
        }
    }

    /**
     * 生成数字验证码
     */
    public String genratePhoneCode() {
        Random random = new Random();

        String code = "";
        for (int i = 0; i < 6; i++) {
            int randomNumber = random.nextInt(10);

            code += randomNumber + "";
        }

        return code;
    }
}
